package com.heima.search.service.Impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.model.common.dtos.PageRequestDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.pojo.ApAssociateWords;
import com.heima.search.pojo.ApUserSearch;
import com.heima.search.service.ApAssociateWordService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.i18nformatter.qual.I18nFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ApAssociateWordServiceImpl implements ApAssociateWordService {

    @Autowired
    private MongoTemplate template;

    @Override
    public ResponseResult search(UserSearchDto dto) {
        if (!StringUtils.isNotBlank(dto.getSearchWords())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        if (dto.getPageSize()>20){
            dto.setPageSize(20);
        }

        Query associateWords = Query.query(Criteria.where("associateWords").regex(".*?\\" + dto.getSearchWords() + ".*"));

        associateWords.limit(dto.getPageSize());
        List<ApAssociateWords> apAssociateWords = template.find(associateWords, ApAssociateWords.class);

        return ResponseResult.okResult(apAssociateWords);
    }
}
